<template>
    <show-modal :title="title" :loading="loading" width="400px" @cancel="cancel" @submit="addSubmit">
        <a-form-model ref="form" :model="form" :rules="rules" v-bind="layout">
            <a-form-model-item label="产品属性" prop="attCode">
                <a-select v-model="form.attCode" :disabled="deviceCode?true:false" show-search optionFilterProp="name" placeholder="请选择产品属性">
                    <a-select-option v-for="item in property" :name="item.attName+item.attCode" :value="item.attCode" :key="item.attCode">
                        {{ item.attName }}
                    </a-select-option>
                </a-select>
            </a-form-model-item>
            <a-form-model-item label="属性值" prop="attValue" v-if="deviceCode">
                <a-input v-model.trim="form.attValue" placeholder="请填写属性值" />
            </a-form-model-item>
        </a-form-model>
    </show-modal>
</template>

<script>
import { rules } from './rules';
import { addInfo, updateInfo } from '@/api/product/property';
import { updateDeviceProperty } from '@/api/device';
export default {
    name: 'propertyInfo',
    props: {
        productCode: String,
        info: Object,
        deviceCode: {
            type:String || null,
            default:''
        },
        property: []
    },
    data() {
        return {
            rules,
            loading: false,
            form: {
                pdtCode: '',
                attCode: undefined
            },
            layout: {
                labelCol: { span: 5 },
                wrapperCol: { span: 19 }
            }
        };
    },
    computed: {
        title() {
            return this.info.id ? '修改属性' : '新增属性';
        }
    },
    created() {
        this.form.pdtCode = this.productCode;
        this.form = { ...this.form, ...this.info };
    },
    methods: {
        //添加
        addSubmit() {
            this.$refs.form.validate(async valid => {
                if (valid) {
                    this.loading = true;
                    try{
                        if (this.form.id) {
                            if(this.deviceCode){
                                await updateDeviceProperty(this.form)
                            }else{
                                await updateInfo(this.form);
                            }
                            this.$message.success('修改成功!');
                        } else {
                            await addInfo(this.form);
                            this.$message.success('添加成功!');
                        }
                        this.$emit('submit');
                    }finally{
                        this.loading = false;
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //取消
        cancel() {
            this.$emit('cancel');
        }
    }
};
</script>
